<template>
	<div class="library_base_info">
		<el-form class="base_info_form" ref="form" size="medium" :model="libraryForm" :rules="libraryRules" :disabled="disabled">
			<el-form-item label="资源库名称" prop="name">
				<el-input class="libname" v-model="libraryForm.name" maxlength="25"></el-input>
				<p class="tips">由汉字、数字、英文字母或下划线组成，长度不超过25字符</p>
			</el-form-item>
			<el-row>
				<el-col :span="12">
					<el-form-item label="入库审核" prop="addAudit">
						<el-switch v-model="libraryForm.addAudit" active-value="1" inactive-value="2"></el-switch>
						<p class="tips">关闭后，文件无需审核，可直接录入</p>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="出库审核" prop="outAudit">
						<el-switch v-model="libraryForm.outAudit" active-value="1" inactive-value="2"></el-switch>
						<p class="tips">关闭后，文件无需审核，可直接出库</p>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="下载审核" prop="downAudit">
						<el-switch v-model="libraryForm.downAudit" active-value="1" inactive-value="2"></el-switch>
						<p class="tips">关闭后，下载无需审核，可直接上传</p>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="录入编目" prop="addCatalog">
						<el-switch v-model="libraryForm.addCatalog" active-value="1" inactive-value="2"></el-switch>
						<p class="tips">关闭后，文件无需编目，可直接上传</p>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="录入标签" prop="addLabel">
						<el-switch v-model="libraryForm.addLabel" active-value="1" inactive-value="2"></el-switch>
						<p class="tips">关闭后，标签无需录入，可直接上传</p>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="库标签">
				<el-select class="liblabel" v-model="libraryForm.libraryList" multiple placeholder="请选择库标签">
					<el-option v-for="(item, index) in libraryTypeData" :key="index" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="资源库封面">
				<el-radio-group v-model="libraryCoverType">
					<el-radio v-for="(item, index) in dictEnums['RESOURCES_CATEGORY']" :key="index" :label="item.value">{{ item.msg }}</el-radio>
					<el-radio label="100">自定义</el-radio>
				</el-radio-group>
				<template v-if="libraryCoverType === '100'">
					<upload-cover ref="upload" :disabled="disabled" @finish="handleUploadFinish"></upload-cover>
				</template>
				<dl :class="['coverlist', { disabled: disabled }]" v-else>
					<dt>
						<img :src="checkedCover" v-if="!!checkedCover" />
					</dt>
					<dd v-for="(item, index) in libraryCoverData" :key="index" :class="{ active: item.attrAddr === checkedCover }" @click="handleSelectCover(item)">
						<img :src="item.attrAddr" />
					</dd>
				</dl>
			</el-form-item>
		</el-form>
		<div class="button" v-if="!disabled">
			<el-button size="medium" @click="handleCloseDialog">取消</el-button>
			<el-button size="medium" type="primary" @click="handleSubmitForm">{{ addOrEdit ? '新增' : '修改' }}</el-button>
		</div>
	</div>
</template>

<script>
import { mapGetters } from 'vuex';
import uploadCover from './uploadCover';
import { getAttachList } from '@/api/global';
import { addedLibrary, updateLibrary } from '@/api/data/tbNetDiskDir';
export default {
	components: { uploadCover },
	inject: ['libraryTypes'],
	props: {
		data: {
			type: Object,
			default() {
				return {};
			}
		},
		disabled: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			libraryForm: {},
			libraryRules: {
				name: [{ required: true, trigger: 'blur', message: '请输入资源库名称' }]
			},
			checkedCover: '',
			libraryCoverType: '1',
			libraryCoverData: []
		};
	},
	computed: {
		...mapGetters(['dictEnums']),
		addOrEdit() {
			return Object.keys(this.data).length === 0;
		},
		libraryTypeData() {
			return this.libraryTypes().filter((item) => item.id !== '-1');
		}
	},
	watch: {
		libraryCoverType: {
			handler(val) {
				if (val === '100') return false;
				this.getLibraryCover(val);
			},
			immediate: true
		},
		data: {
			handler(data) {
				console.log(data);
				if (!data.coverInfo) {
					this.libraryForm = {};
					this.checkedCover = window.staticPath + this.libraryCoverData[0]?.attrAddr;
					return false;
				} else if (data.coverInfo.category === '-1') {
					this.libraryCoverType = '100';
					this.$nextTick(() => {
						this.$refs['upload'].coverImage = window.staticPath + data.coverInfo.attrAddr;
					});
				} else {
					this.checkedCover = window.staticPath + data.coverInfo.attrAddr;
					this.libraryCoverType = data.coverInfo.category;
				}
				this.libraryForm = this.formatInitParams(data);
			},
			immediate: true
		}
	},
	methods: {
		//格式化初始参数
		formatInitParams(data) {
			let params = { ...data };
			let libList = params.libDirList.map((item) => item.libraryId);
			params['libraryList'] = this.$lodash.uniq(libList);
			return params;
		},

		//获取资源库封面
		async getLibraryCover(category) {
			let params = { page: 1, limit: 10, type: 5, category };
			let result = await getAttachList(params).then((res) => res.data);
			if (result.code === '0') {
				let datas = result.data || [];
				this.libraryCoverData = datas.map((n) => {
					return { ...n, attrAddr: window.staticPath + n.attrAddr };
				});
				if (!!datas[0]) {
					this.libraryForm['coverId'] = datas[0].id;
					this.checkedCover = window.staticPath + datas[0].attrAddr;
				}
			}
		},

		//选择封面
		handleSelectCover(data) {
			if (this.disabled) return false;
			this.checkedCover = data.attrAddr;
			this.libraryForm['coverId'] = data.id;
		},

		//关闭弹窗
		handleCloseDialog() {
			this.$emit('hand', 'close');
		},

		//提交库基本信息
		handleSubmitForm() {
			this.$refs['form'].validate((valid) => {
				if (!valid) return false;
				if (this.libraryCoverType === '100') {
					this.$refs['upload'].handleUpload();
				} else {
					this.libraryInfoRequest();
				}
			});
		},

		//库封面上传成功
		handleUploadFinish(data) {
			this.libraryForm['coverId'] = data.id;
			this.libraryInfoRequest();
		},

		//格式化表单参数
		formatFormParams() {
			let params = { ...this.libraryForm };
			params['libraryList'] = params.libraryList.map((item) => {
				return { relId: item, operType: '1' };
			});
			return params;
		},

		//库信息新增编辑请求
		async libraryInfoRequest() {
			let params = this.formatFormParams();
			let libraryFun = eval(this.addOrEdit ? addedLibrary : updateLibrary);
			let result = await libraryFun(params).then((res) => res.data);
			if (result.code === '0') {
				this.$emit('hand', 'refresh');
				this.$message.success(`${this.addOrEdit ? '添加' : '修改'}资源库成功`);
			} else {
				this.$message.error(`${this.addOrEdit ? '添加' : '修改'}资源库失败`);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.library_base_info ::v-deep {
	display: flex;
	flex-direction: column;
	flex: 1;
	height: 100%;
	overflow: hidden;

	.button {
		padding: 16px;
		text-align: right;
		border-top: solid 1px #ebeef5;
	}
}

.base_info_form ::v-deep {
	flex: 1;
	padding: 20px 0 0 32px;
	overflow: auto;

	p.tips {
		color: #999;
		line-height: 1;
		margin-top: 6px;
	}

	.el-row {
		margin-right: 30px;
	}

	.libname {
		width: 680px;
	}

	.liblabel {
		width: 719px;
	}

	dl.coverlist {
		width: 770px;
		height: 119px;
		overflow: hidden;

		&.disabled {
			filter: grayscale(75%);
		}

		dt {
			float: left;
			width: 208px;
			height: 117px;
			margin-bottom: 9px;
		}

		dd {
			float: left;
			width: 96px;
			height: 54px;
			margin: 0 0 9px 9px;
			cursor: pointer;
			position: relative;
		}

		img {
			display: block;
			width: 100%;
			height: 100%;
			object-fit: cover;
			box-sizing: border-box;
		}

		dd.active::before {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			content: '\e664';
			font-family: 'iconfont';
			line-height: 45px;
			text-align: center;
			color: #fff;
			font-weight: bold;
			background-color: rgba(0, 0, 0, 0.25);
		}

		&:not(.disabled) dd:hover img {
			border: solid 2px var(--primary-hover);
		}
	}

	.el-form-item {
		margin-bottom: 18px;
	}

	.el-form-item__label {
		color: #333;
		font-weight: bold;
	}

	.el-form-item__error {
		top: 8px;
		left: 650px;
		font-size: 14px;
	}
}
</style>
